/*
 * 路比信息科技有限公司
 * @author kinwyb<kinwyb@mp189.com>
 * @date 2015-7-4
 */
package lcfgly.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * Http请求
 *
 * @author lcfgly
 */
@Deprecated
public class LHttp {

    private final CloseableHttpClient httpclient = HttpClients.createDefault();
    private final String url;
    private Charset charset = Charset.forName("utf8");

    /**
     * 请求的URL
     * @param url 
     */
    public LHttp(String url) {
        this.url = url;
    }

    /**
     * 设置编码
     *
     * @param charset
     */
    public void setCharset(String charset) {
        this.charset = Charset.forName(charset);
    }

    /**
     * 发送POST请求
     *
     * @param params
     * @return
     * @throws IOException
     */
    public String post(Map<String, String> params) throws IOException {
        HttpPost post = new HttpPost(url);
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String value = params.get(key);
                NameValuePair pair = new BasicNameValuePair(key, value);
                nvps.add(pair);
            }
            post.setEntity(new UrlEncodedFormEntity(nvps, charset));
        }
        CloseableHttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, charset);
    }

    /**
     * 发送GET请求
     *
     * @return
     * @throws java.io.IOException
     */
    public String get() throws IOException {
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(get);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, charset);
    }

    /**
     * 以body方式发送请求参数
     * @param params
     * @return
     * @throws IOException 
     */
    public String postBody(String params)throws IOException{
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(params, charset));
        CloseableHttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, charset);
    }
    
}
